<template>
  <div>
    <!-- 设备列表 -->
    <el-card class="device_card" style="height: calc(100vh - 7rem)">
      <div class="w-full flex justify-end items-center">
        <el-button type="primary" icon="Plus" @click="openDrawer({ id: 0 })"
          >新增</el-button
        >
      </div>

      <el-table :data="tableData" style="height: calc(100vh - 12rem)">
        <el-table-column prop="deviceName" label="设备名称" />
        <el-table-column prop="outCode" label="设备外码" />
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="typeName" label="设备型号" />
        <el-table-column prop="tagsDescription" label="标签" />
        <el-table-column prop="status" label="设备状态">
          <template #default="{ row }">
            <el-tag v-if="row.status == 1" type="success"> 已激活 </el-tag>
            <el-tag v-else type="warning"> 未激活 </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="350px">
          <template #default="{ row }">
            <el-button type="warning" link @click="handleActivationCode(row)">
              <el-icon> <Link /> </el-icon>获取激活码
            </el-button>
            <el-button type="primary" link @click="openDrawer(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="primary" link @click="openDataDrawer(row)">
              <el-icon><CameraFilled /></el-icon>
              数据记录
            </el-button>
            <el-button type="primary" link @click="openLongDrawer(row)">
              <el-icon><Link /></el-icon>
              远程控制
            </el-button>
            <el-button type="primary" link @click="openBridgeDrawer(row)">
              <el-icon><Lightning /></el-icon>
              数据桥列表
            </el-button>
            <el-button type="danger" link @click="handleUnbind(row)">
              <el-icon><FolderDelete /></el-icon>解绑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <PagingQuery
        :page="page"
        :pageSize="pageSize"
        :total="total"
        @getList="getList"
        class="mt-2"
      />
    </el-card>

    <!-- 1.新增或者编辑设备 -->
    <el-drawer
      v-model="drawer"
      :title="detail.id == 0 ? '新增设备' : '编辑设备'"
      size="40%"
      destroy-on-close
    >
      <InsertUpdateDevice :detail="detail" @handleBack="handleSuccessDevice" />
    </el-drawer>

    <!-- 3.获取激活码 -->
    <el-drawer
      v-model="active_drawer"
      title="获取激活码"
      size="40%"
      destroy-on-close
    >
      <GetActivationCode
        :detailForm="detailForm"
        @handleClose="handleCodeClose"
        @handleCancel="handleCancel"
      />
    </el-drawer>

    <!-- 3.1 激活码详情 -->
    <el-dialog
      v-model="active_detail_drawer"
      title="激活码详情"
      width="500px"
      top="22vh"
      destroy-on-close
      style="text-align: center"
    >
      <ActivationCodeDetail
        :detailForm="detailForm"
        @handleCancel="handleCancel"
      />
    </el-dialog>

    <!-- 4.远程控制 -->
    <el-drawer v-model="long_drawer" size="80%" destroy-on-close>
      <template #header>
        <div class="font-medium text-[0.8rem]">
          <span>设备名称: {{ long_detail.deviceName }} , </span>
          <span>设备外码：{{ long_detail.deviceSn }}</span>
        </div>
      </template>
      <LongControl :detailForm="long_detail" />
    </el-drawer>

    <!-- 5.数据桥列表 -->
    <el-drawer v-model="bridge_drawer" size="80%" destroy-on-close>
      <template #header>
        <div class="font-medium text-[0.8rem]">
          <span>设备名称: {{ bridge_detail.deviceName }} , </span>
          <span>设备外码(发送端)：{{ bridge_detail.outCode }}</span>
        </div>
      </template>
      <DataBridgeList :detailForm="bridge_detail" />
    </el-drawer>

    <!-- 6.数据记录 -->
    <el-drawer v-model="data_drawer" size="80%" destroy-on-close>
      <template #header>
        <div class="font-medium text-[0.8rem]">
          <span>设备名称: {{ data_detail.deviceName }} , </span>
          <span>设备型号：{{ data_detail.typeName }}, </span>
          <span>品牌：{{ data_detail.brandName }}</span>
        </div>
      </template>
      <DataLogging :detailForm="data_detail" />

      <template #footer>
        <el-button @click="data_drawer = false">关闭</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import PagingQuery from "@/components/PagingQuery.vue";
import InsertUpdateDevice from "./component/InsertUpdateDevice.vue";
import GetActivationCode from "./component/GetActivationCode.vue";
import ActivationCodeDetail from "./component/ActivationCodeDetail.vue";
import LongControl from "./component/LongControl.vue";
import DataBridgeList from "./component/DataBridgeList.vue";
import DataLogging from "./component/DataLogging.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  ListMyDevice,
  UnbindDevice,
} from "../../../../wailsjs/go/api/DeviceApi.js";

onMounted(() => {
  getList();
});

const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
async function getList(e) {
  if (e) {
    page.value = e.page;
    pageSize.value = e.pageSize;
  }
  handleApiResponse(() =>
    ListMyDevice({
      page: page.value,
      pageSize: pageSize.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  });
}

// 1.新增或者编辑设备
const drawer = ref(false);
const detail = ref(0);
const openDrawer = (row) => {
  detail.value = cloneDeep(row); // 0 新增 !0 编辑
  drawer.value = true;
};
const handleSuccessDevice = (val) => {
  drawer.value = false;
  if (val == 1) {
    getList();
  }
};

// 3.获取激活码
const detailForm = ref({});
const active_drawer = ref(false); // 获取激活码抽屉
const active_detail_drawer = ref(false); // 获取激活码成功详情抽屉
const handleActivationCode = (item) => {
  // 获取当前秒级时间戳
  const date = new Date();
  date.setMilliseconds(0);
  const timestamp = date.getTime() / 1000;

  // 根据outCode获取缓存里的激活码
  const activationCodeForm = JSON.parse(sessionStorage.getItem(item.outCode));

  // 通过outCode和categoryId来判断是否是同一个设备
  if (
    activationCodeForm &&
    item.outCode == activationCodeForm.outCode &&
    item.categoryId == activationCodeForm.categoryId
  ) {
    if (activationCodeForm.expireAt <= timestamp) {
      // 激活码已过期,请重新获取
      detailForm.value = item;
      active_drawer.value = true;
      ElMessage.warning("激活码已过期,请重新获取");
      sessionStorage.removeItem(item.outCode);
      return;
    }
    handleCodeClose(item); // 该设备已授权"
  } else {
    // 未授权
    detailForm.value = item;
    active_drawer.value = true;
  }
};
const handleCodeClose = ($event) => {
  // 提交成功后的处理方法
  detailForm.value = $event;
  active_drawer.value = false;
  active_detail_drawer.value = true;
};
const handleCancel = () => {
  // 关闭激活码详情抽屉
  active_detail_drawer.value = false;
};

// 4.远程控制
const long_drawer = ref(false);
const long_detail = ref({});
const openLongDrawer = (row) => {
  long_detail.value = cloneDeep(row);
  long_drawer.value = true;
};

// 5.数据桥列表
const bridge_drawer = ref(false);
const bridge_detail = ref({});
const openBridgeDrawer = (row) => {
  bridge_detail.value = cloneDeep(row);
  bridge_drawer.value = true;
};

// 6.数据记录
const data_drawer = ref(false);
const data_detail = ref({});
const openDataDrawer = (row) => {
  data_detail.value = cloneDeep(row);

  data_drawer.value = true;
};

// 7.解绑
const handleUnbind = (row) => {
  ElMessageBox.confirm("你确定解绑该设备吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      UnbindDevice({
        id: row.id,
        deviceSn: row.deviceSn,
      })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("解绑成功");
        getList();
      }
    });
  });
};
</script>

<style scoped lang="scss">
.device_card :deep(.el-card__body) {
  @apply px-[0.5rem] py-[0.3rem];
}
</style>